package com.example.demo.controller;

import com.example.demo.common.*;
import com.example.demo.entity.ArticleInfo;
import com.example.demo.entity.UserInfo;
import com.example.demo.entity.vo.ArticleInfoVo;
import com.example.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("art")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/add")
    public AjaxResult add(ArticleInfo articleInfo, HttpServletRequest httpServletRequest){
        //1.非空校验
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle())){
            return AjaxResult.fail(-1,"标题不能为空");
        }
        if (!StringUtils.hasLength(articleInfo.getContent())){
            return AjaxResult.fail(-1,"正文不能为空");
        }
        //2.组装数据，得到uid
        UserInfo userInfo = UserSessionTools.getLoginUser(httpServletRequest);
        if (userInfo == null){
            return AjaxResult.fail(-1,"请登录后再操作");
        }
        articleInfo.setUid(userInfo.getId());
        //3.持久化，将结果返回给前端
        int result = articleService.add(articleInfo);
        return AjaxResult.success(result);

    }

    /**
     * 修改文章，初识化文章修改页面
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/initArticle")
    public AjaxResult initArticle(Integer id,HttpServletRequest request){
        //非空校验
        if (id == null|| id<=0) {
            return AjaxResult.fail(-1,"参数异常");
        }
        //获取uid
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if (userInfo==null){
            return AjaxResult.fail(-1,"在操作前请先登录");
        }
        // 根据id查询这个uid的作者
        ArticleInfo articleInfo = articleService.getDetailByIdAndUid(id,userInfo.getId());
        return AjaxResult.success(articleInfo);
    }

    /**
     * 获取文章的详细信息，但是需要进行鉴权（判断权限的归属人是否是当前登录用户
     * @param id
     * @param httpServletRequest
     * @return
     */
    @RequestMapping("/getdetail")

    public AjaxResult getDetailByIdAndUid(Integer id, HttpServletRequest httpServletRequest){
        if (id==null||id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        UserInfo userInfo = UserSessionTools.getLoginUser(httpServletRequest);

        return AjaxResult.success(articleService.getDetailByIdAndUid(id,userInfo.getId())) ;
    }

    /**
     * 修改文章并发表文章
     * @param articleInfo
     * @param httpServletRequest
     * @return
     */
    @RequestMapping("/update")
    public AjaxResult update(ArticleInfo articleInfo,HttpServletRequest httpServletRequest){
        //非空校验
        if (null == articleInfo || articleInfo.getId()<=0 ||
        !StringUtils.hasLength(articleInfo.getTitle())||
        !StringUtils.hasLength(articleInfo.getContent())||
        !StringUtils.hasLength(articleInfo.getDescription())){

            return AjaxResult.fail(-1,"参数有误");
        }
        //拿uid和id 填充到articleInfo对象中（修改时要验权
        UserInfo userInfo = GetUserSessionTools.getLoginUser(httpServletRequest);
        if (userInfo == null){
            return AjaxResult.fail(-1,"参数异常");
        }


        articleInfo.setUid(userInfo.getId());
        //更新修改时间
        articleInfo.setUpdatetime(LocalDateTime.now());
        //发布状态
        articleInfo.setState(1);
        int result = articleService.update(articleInfo);
        return AjaxResult.success(result);
    }
    /**
     * 博客列表 没有加权校验的 没登录也能看
     */
//    @RequestMapping("/getdetail")
//    public AjaxResult getDetail(Integer id){
//        if (id == null || id <= 0){
//            return AjaxResult.fail(-1,"参数有误");
//        }
//        ArticleInfoVo articleInfoVo = articleService.getDetail(id);
//        return AjaxResult.success(articleInfoVo);
//    }

    /**
     * 阅读量
     */
    @RequestMapping("/addrcount")
    public AjaxResult addRCount(Integer id){
        if (id==null || id<0){
            return AjaxResult.fail(-1,"参数有误");
        }
        int result = articleService.addRCount(id);
        return AjaxResult.success(result);
    }

    /**
     * 查询指定用户所有文章，用来更新用户文章数
     * @param id
     * @return
     */
    @RequestMapping("/countart")
    public AjaxResult countArticle(Integer id){
        ArticleInfo articleInfo = articleService.selectArticleById(id);

        int uid = articleInfo.getUid();

        List<ArticleInfo> lists = articleService.countArticle(uid);

        return AjaxResult.success(lists.size());
    }

    /**
     * 查询当前用户已经发表的所有文章并且将其返回
     * @param request
     * @return
     */
    @RequestMapping("getAllArticle")
    public AjaxResult getAllArticle(HttpServletRequest request){
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if (userInfo==null){
            return AjaxResult.fail(-1,"参数异常");
        }

        int uid = userInfo.getId();
        List<ArticleInfo> list = articleService.getAllArticle(uid);

        //截取摘要，处理关键字
        for (ArticleInfo info:list){
            String res = RemoveKeyWords.removeKeywords(info.getContent());
            info.setContent(AbstractContentTools.SubContent(res,ApplicationVariable.maxLength));

        }

        return AjaxResult.success(list);
    }

    /**
     * 删除指定文章
     * @param id
     * @param request
     * @return
     */


    @RequestMapping("/del")
    public AjaxResult del(Integer id,HttpServletRequest request){
        if (id==null || id<=0){
            return AjaxResult.fail(-1,"参数错误");
        }
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if (userInfo==null){
            return AjaxResult.fail(-1,"参数异常");
        }
        int result = articleService.del(id,userInfo.getId());
        return AjaxResult.success(result);
    }

    /**
     * 获取每一页中所以用户已经发表的文章
     * @param pageSize
     * @param pageIndex
     * @return
     */
    @RequestMapping("/getAllArticleByPage")
    public AjaxResult getAllArticleByPage(Integer pageSize, Integer pageIndex ){
        //默认值处理
        if (pageSize == null || pageSize <= 0 ){
            pageSize = 2; //与前端约定好
        }
        if (pageIndex == null || pageIndex <1){
            pageIndex = 1;
        }
        //分页公式
        int offset = (pageIndex - 1)*pageSize;
        List<ArticleInfo>list = articleService.getAllArticleByPage(pageSize,offset,1);
        //多线程并发循环
        for (ArticleInfo info:list){
            String res = RemoveKeyWords.removeKeywords(info.getContent());
            info.setContent(AbstractContentTools.SubContent(res,ApplicationVariable.maxLength));
        }

        return AjaxResult.success(list);
    }


    @RequestMapping("/getcount")
    public AjaxResult getCount(){
        return AjaxResult.success(articleService.getCount());
    }


    /**
     *不同页加载当前用户发布的文章
     * @param pageSize
     * @param pageIndex
     * @param request
     * @return
     */
    @RequestMapping("/getAllArticleByPageFromUser")
    public AjaxResult getAllArticleByPageFromUser(Integer pageSize, Integer pageIndex, HttpServletRequest request){
        UserInfo userInfo = UserSessionTools.getLoginUser(request);
        if (userInfo == null){
            return AjaxResult.fail(-1,"参数异常");
        }

        if (pageSize == null || pageSize <= 0){
            pageSize = 2;
        }
        if (pageIndex == null || pageIndex <= 0){
            pageIndex = 1;
        }

        int offset = (pageIndex - 1)* pageSize;

        List<ArticleInfo> list = articleService.getAllArticleByPageFromUser(pageSize,offset,userInfo.getId(),1);

        for (ArticleInfo info:list){
            String res = RemoveKeyWords.removeKeywords(info.getContent());
            info.setContent(AbstractContentTools.SubContent(res,ApplicationVariable.maxLength));
            System.out.println("文章摘要："+info.getDescription());
        }
        return AjaxResult.success(list);
    }

    /**
     * 聚合查询当前用户已发表的文章数 - 根据 uid
     */
    @RequestMapping("/getArticleFromUser")
    public AjaxResult getArticleFromUser(HttpServletRequest request) {
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if (userInfo == null) return AjaxResult.fail(-1, "参数异常");
        int result = articleService.getArticleFromUser(userInfo.getId(), 1);
        return AjaxResult.success(result);
    }

    /**
     * 聚合查询所有人已发表的文章数
     */
    @RequestMapping("/allarticle")
    public AjaxResult getArticle() {
        int result = articleService.getArticle(1);
        return AjaxResult.success(result);
    }

    /**
     * 查询当前用户并设置其信息栏头像
     *
     * @param id 当前文章 id
     */
    @RequestMapping("/initimage")
    public AjaxResult initimage(Integer id) {
        // 1. 数据效验
        if (id == null || id <= 0) return AjaxResult.fail(-1, "参数异常");

        // 2. 多表联查, 根据文章自增 id  确认文章归属人
        ArticleInfoVo articleInfoVo = articleService.getImagePath(id);

        return AjaxResult.success(articleInfoVo);
    }

    /**
     * 保存草稿
     * @param articleInfo
     * @param request
     * @return
     */
    @RequestMapping("/savearticle")
    @Transactional
    public AjaxResult saveArticle(ArticleInfo articleInfo, HttpServletRequest request){
        //数据校验
        if (!StringUtils.hasLength(articleInfo.getContent())){
            return AjaxResult.fail(-1,"当前正文中无内容");
        }
        //得到当前登录用户的id设置发布文章的uid
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if(userInfo== null){
            return AjaxResult.fail(-1,"请先登录，再进行操作");
        }

        //用户表id关联uid
        articleInfo.setUid(userInfo.getId());

        //设置发布状态为未发布
        articleInfo.setState(2);

        //保存文章
        int result = articleService.saveArticle(articleInfo);
        return AjaxResult.success(result);
    }

    /**
     * 当前用户未发布的所有文章
     * @param pageSize  一页最大
     * @param pageIndex  当前第几页
     * @param request
     * @return
     */
    @RequestMapping("/getAllArticleByPageNotSub")
    public AjaxResult getAllArticleByPageNotSub(Integer pageSize, Integer pageIndex, HttpServletRequest request){
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if (userInfo == null){
            return AjaxResult.fail(-1,"参数异常");
        }

        // 首次加载在首页, 没有传入 pageSize
        if (pageSize == null || pageSize <= 0) {
            pageSize = 2;
        }

        if (pageIndex == null || pageIndex <= 0) {
            pageIndex = 1; // 默认为第一页
        }

        int offset = (pageIndex - 1) * pageSize; // 分页公式

        List<ArticleInfo> list = articleService.getAllArticleByPageNotSub(pageSize, offset, userInfo.getId(), 2);

        // 文章摘要处理  去除关键字  截取文章
        for (ArticleInfo item : list) {
            String removeKeyWords = RemoveKeyWords.removeKeywords(item.getContent());
            item.setContent(AbstractContentTools.SubContent(removeKeyWords, ApplicationVariable.maxLength));
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询用户未发布的文章总数
     * @param request
     * @return
     */

    @RequestMapping("/getArticleNotSub")
    public AjaxResult getArticleNotSub(HttpServletRequest request){
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if (userInfo==null){
            return AjaxResult.fail(-1,"参数异常");
        }
        int result = articleService.getArticleNotSub(userInfo.getId(),2);
        return AjaxResult.success(result);
    }

    /**
     * 自动保存
     * @param articleInfo
     * @param request
     * @return
     */
    @RequestMapping("/autosavearticle")
    @Transactional
    public AjaxResult autoSaveArticle(ArticleInfo articleInfo, HttpServletRequest request){
        UserInfo userInfo = GetUserSessionTools.getLoginUser(request);
        if (userInfo == null){
            return AjaxResult.fail(-1,"请先登录，再进行操作");
        }

        articleInfo.setUid(userInfo.getId());

        articleInfo.setState(2);

        int result = articleService.autoSaveArticle(articleInfo);
        return AjaxResult.success(result);
    }

}
